from OWRpy import *
import redRi18n
_ = redRi18n.get_(package = 'base')

import signals 
import redRGUI 

class fusionLevel(OWRpy): 
    globalSettingsList = ['commit']
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)

        # R code for generating the fusion level plot
        self.R('source(\''+unicode(os.path.join(redREnviron.directoryNames['libraryDir'], 'ecology', 'widgets', 'fusionLevel.R')).replace('\\', '//')+'\')')
        
        # Python variables
        self.data = {}
        self.RFunctionParam_object = ''
        self.RFunctionParam_clust = ''
        
        #Inputs
        self.inputs.addInput('id0', 'Initial data (before dissimilarity)', signals.base.RDataFrame, self.processobject) 
        self.inputs.addInput('id1', 'Cluster analysis', signals.base.RList, self.processclust) # creer un signal pour dissimilarity object
        
        #GUI
        self.RFunctionParam_GUI_tabs = redRGUI.base.tabWidget(self.controlArea)
        self.RFunctionParam_GUI_tabsPlot = self.RFunctionParam_GUI_tabs.createTabPage(name = "Plot",orientation='vertical')
        self.plotArea = redRGUI.plotting.redRPlot(self.RFunctionParam_GUI_tabsPlot, label = "Plot", displayLabel = False)
        #self.plotArea.topArea.hide()
        
        #Commit
        self.commit = redRGUI.base.commitButton(self.bottomAreaRight, _("Commit"), alignment=Qt.AlignLeft, 
        callback = self.commitFunction, processOnInput=True)
        
        
    def processobject(self, data):
        if not self.require_librarys(["stats"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_object=data.getData()
            self.data = data
            if self.commit.processOnInput():
                self.commitFunction()
        else:
            self.RFunctionParam_clust=''
            
    def processclust(self, data):
        if not self.require_librarys(["stats"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_clust=data.getData()
            self.data = data
            if self.commit.processOnInput():
                self.commitFunction()
        else:
            self.RFunctionParam_clust=''

    def commitFunction(self):
        
        if unicode(self.RFunctionParam_clust) == '':
            self.status.setText('No cluster data.')
            return
        if unicode(self.RFunctionParam_object) == '':
            self.status.setText('No initial data.')
            return

        self.R('nRow<-nrow('+unicode(self.RFunctionParam_object)+')', wantType = 'NoConversion')
        self.plotArea.plotMultiple(query = 'height='+unicode(self.RFunctionParam_clust)+'$height, nRow=nRow', function = 'fusionLevel')